import os
import json
import logging
from typing import Any, Dict, Optional
from pathlib import Path

class ConfigManager:
    """配置管理器"""
    def __init__(self, config_dir: str = "config"):
        self.config_dir = Path(config_dir)
        self.config_file = self.config_dir / "config.json"
        self.logger = logging.getLogger(__name__)
        
        # 确保配置目录存在
        self.config_dir.mkdir(parents=True, exist_ok=True)
        
        # 加载配置
        self.config = self._load_config()
    
    def _load_config(self) -> Dict:
        """加载配置"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    # 合并用户配置和默认配置
                    return self._merge_configs(self._get_default_config(), user_config)
        except Exception as e:
            self.logger.error(f"Failed to load config: {str(e)}")
        
        return self._get_default_config()
    
    def _get_default_config(self) -> Dict:
        """获取默认配置"""
        return {
            "server": {
                "default_host": "192.168.10.6",
                "default_port": "11434",
                "timeout": 30,
                "max_retries": 3,
                "retry_delay": 1
            },
            "chat": {
                "max_context_length": 2048,
                "temperature": 0.7,
                "top_p": 0.9,
                "max_tokens": 500,
                "max_input_length": 1000,
                "stream": True
            },
            "ui": {
                "theme": "light",
                "language": "zh_CN",
                "show_timestamps": True,
                "show_thinking": True,
                "auto_clear": False,
                "max_messages_shown": 50
            },
            "session": {
                "auto_save": True,
                "save_interval": 300,  # 5分钟
                "max_sessions": 100,
                "session_dir": "chat_sessions"
            },
            "network": {
                "scan_timeout": 0.5,
                "max_workers": 50,
                "default_networks": []
            }
        }
    
    def _merge_configs(self, default: Dict, user: Dict) -> Dict:
        """递归合并配置"""
        result = default.copy()
        
        for key, value in user.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._merge_configs(result[key], value)
            else:
                result[key] = value
        
        return result
    
    def save_config(self) -> bool:
        """保存配置"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            self.logger.error(f"Failed to save config: {str(e)}")
            return False
    
    def get_config(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        try:
            value = self.config
            for k in key.split('.'):
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set_config(self, key: str, value: Any) -> bool:
        """设置配置值"""
        try:
            keys = key.split('.')
            config = self.config
            
            # 遍历到最后一个键之前
            for k in keys[:-1]:
                if k not in config:
                    config[k] = {}
                config = config[k]
            
            # 设置最后一个键的值
            config[keys[-1]] = value
            return True
        except Exception as e:
            self.logger.error(f"Failed to set config {key}: {str(e)}")
            return False
    
    def update_config(self, updates: Dict) -> bool:
        """批量更新配置"""
        try:
            for key, value in updates.items():
                self.set_config(key, value)
            return self.save_config()
        except Exception as e:
            self.logger.error(f"Failed to update config: {str(e)}")
            return False
    
    def reset_config(self) -> bool:
        """重置为默认配置"""
        try:
            self.config = self._get_default_config()
            return self.save_config()
        except Exception as e:
            self.logger.error(f"Failed to reset config: {str(e)}")
            return False 